#!/bin/sh
#
# mediatomb This script starts and stops the mediatomb daemon
#
# chkconfig: - 95 30
# processname: mediatomb
# description: mediatomb is a daemon process which provides a UPnP service
# config: /opt/etc/mediatomb
# config: /opt/etc/mediatomb/config.xml
# pidfile: /opt/var/run/mediatomb.pid

# Source default mediatomb configuration
. /opt/etc/mediatomb.conf

MEDIATOMB="-d -u $MT_USER -g $MT_GROUP -P $MT_PIDFILE -l $MT_LOGFILE -m $MT_HOME -f $MT_CFGDIR -p $MT_PORT"

[ -f /opt/bin/mediatomb ] || exit 0

[ -e /opt/etc/default/mediatomb ] && . /opt/etc/default/mediatomb

# By default it's all good
RETVAL=0

# See how we were called.
case "$1" in
  start)
    if [ ${MT_ENABLE} = false ] ; then
        echo "mediatomb startup is disabled in /opt/etc/default/mediatomb"
        exit 0
    fi

    # Check if MT is already running
    if [ -e /opt/var/lock/mediatomb ] ; then
        $0 stop
    fi

    # Start daemon.
    touch $MT_PIDFILE
    chown $MT_USER.$MT_GROUP $MT_PIDFILE

    mkdir -p "/$MT_HOME/$MT_CFGDIR"
    chown  $MT_USER.$MT_GROUP "/$MT_HOME/$MT_CFGDIR"
    
    echo -n "Starting mediatomb: "
    
    /opt/bin/mediatomb $MEDIATOMB $MT_OPTIONS
    
    RETVAL=$?
        if [ $RETVAL = 0 ] ; then 
            touch /opt/var/lock/mediatomb
            echo "ok"
        else
            rm -f ${MT_PIDFILE}
            echo "failed"
        fi
        ;;
  stop)
        # Stop daemons.
        echo -n "Shutting down mediatomb: "

    if [ -f ${MT_PIDFILE} ] ; then
        kill `cat ${MT_PIDFILE}` 2>/dev/null
    else
        killall mediatomb 2>/dev/null
    fi
        RETVAL=$?
        if [ $RETVAL = 0 ] ; then
            rm -f /opt/var/lock/mediatomb
            rm -f ${MT_PIDFILE}
            echo "ok"
        else
            echo "failed"
        fi
        
        ;;
  restart)
        $0 stop
        $0 start
        ;;
  condrestart)
       [ -e /opt/var/lock/mediatomb ] && $0 restart
       ;;
  *)
    $0 start
    ;;
esac

exit $RETVAL
